# 模块导入
from . import User
from . import database

# User表的mapper
# 测试完成
class UserMapper:
    # query
    # 根据id查询
    # <User 1>
    @staticmethod
    def query_id(id):
        return User.query.get(id)

    # 查询所有
    # [<User 1>, <User 2>, ...]
    @staticmethod
    def query_all():
        return User.query.filter().all()

    # 根据邮箱查询
    # <User 1>
    @staticmethod
    def query_email(email):
        return User.query.filter_by(email=email).first()

    # 模糊查询
    # [<User 1>, <User 2>, ...]
    @staticmethod
    def query_email_like(keyword):
        return User.query.filter(User.email.like('%'+keyword+'%')).all()

    # 根据用户名查询
    # [<User 1>, <User 2>, ...]
    @staticmethod
    def query_username(username):
        return User.query.filter_by(username=username).all()

    # 模糊查询
    # [<User 1>, <User 2>, ...]
    @staticmethod
    def query_username_like(keyword):
        return User.query.filter(User.username.like('%'+keyword+'%')).all()

    # 根据性别查询
    # [<User 1>, <User 2>, ...]
    @staticmethod
    def query_sex(sex):
        return User.query.filter_by(sex=sex).all()

    # 根据年龄范围查询
    # [<User 1>, <User 2>, ...]
    @staticmethod
    def query_age(age_min, age_max):
        return User.query.filter(User.age.between(age_min, age_max)).all()

    # insert
    # 部分插入，部分为默认值
    @staticmethod
    def insert(username, email):
        user = User(username=username, email=email)
        database.session.add(user)
        database.session.commit()
        return "insert success"

    # 全部指定插入
    @staticmethod
    def insert_param(username, email, sex, age, avatar_url):
        user = User(username=username, email=email, sex=sex, age=age, avatar_url=avatar_url)
        database.session.add(user)
        database.session.commit()
        return "insert success"

    # update
    # email不能改
    @staticmethod
    def update(user_id, username, sex, age, avatar_url):
        user = User.query.get(user_id)
        user.username = username
        user.sex = sex
        user.age = age
        user.avatar_url = avatar_url
        database.session.add(user)
        database.session.commit()
        return "update success"

    # delete
    @staticmethod
    def delete(user_id):
        user = User.query.get(user_id)
        database.session.delete(user)
        database.session.commit()
        return "delete success"
